#!/usr/bin/env bash

# Copyright 2024 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /shell_lib.sh

function __config__(){
  cat <<EOF
configVersion: v1
kubernetes:
  - name: nodeUsers
    apiVersion: deckhouse.io/v1
    kind: NodeUser
    queue: "nodeuser"
    group: main
    executeHookOnEvent: []
    executeHookOnSynchronization: false
    keepFullObjectsInMemory: false
    jqFilter: |
      {
        "name": .metadata.name,
        "uid": .spec.uid,
        "nodeGroups": .spec.nodeGroups
      }
kubernetesValidating:
- name: nodeuser-unique.deckhouse.io
  group: main
  rules:
  - apiGroups:   ["deckhouse.io"]
    apiVersions: ["*"]
    operations:  ["CREATE", "UPDATE"]
    resources:   ["nodeusers"]
    scope:       "Cluster"
EOF
}

function __main__() {
  name=$(context::jq -r '.review.request.object.metadata.name')
  uid=$(context::jq -r '.review.request.object.spec.uid')
  nodeGroups=$(context::jq -r '.review.request.object.spec.nodeGroups[]')
  operation=$(context::jq -r '.review.request.operation')
  passwordHash=$(context::jq -r '.review.request.object.spec.passwordHash')

  snapshots=$(context::jq -cr --arg name "$name" '[.snapshots.nodeUsers[].filterResult | select(.name==$name | not)]')

  if [ $(jq -cr --arg uid "$uid" '[.[] | select(.uid==($uid | tonumber)) | select(.nodeGroups | index("*"))] | length' <<< "$snapshots") -gt 0 ]; then
    cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":false, "message":"The user with the uid: ${uid} already exists in the nodeGroup: \"*\"" }
EOF
    return 0
  fi

  for nodeGroup in "$nodeGroups"; do
    if [ "$nodeGroup" = "*" ] && [ $(jq -cr --arg uid "$uid" '[.[] | select(.uid==($uid | tonumber)) ] | length' <<< "$snapshots") -gt 0 ]; then
      cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":false, "message":"The user with the uid: ${uid} already exists in the nodeGroup: ${nodeGroup}" }
EOF
      return 0
    fi

    if [ $(jq -cr --arg uid "$uid" --arg nodeGroup "$nodeGroup" '[.[] | select(.uid==($uid | tonumber)) | select(.nodeGroups | index($nodeGroup))] | length' <<< "$snapshots") -gt 0 ]; then
      cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":false, "message":"The user with the uid: ${uid} already exists in the nodeGroup: ${nodeGroup}" }
EOF
      return 0
    fi
  done

if [ -z "$passwordHash" ] || [ "$passwordHash" = "null" ]; then
    cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed": true, "warnings": ["Password hash is empty. This may not be secure and it may be prohibited by PAM settings."] }
EOF
      return 0
  fi

  cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":true}
EOF

}

hook::run "$@"
